package net.asfun.jvalog.domain;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.jdo.Query;

import net.asfun.jvalog.po.Map;
import net.asfun.jvalog.service.Jdoer;
import net.asfun.jvalog.service.JdoerFactory;
import net.asfun.jvalog.task.UpdateManager;

public class Config {
	
	public static final String TYPE_BLOG = "blog";
	
	private Map map;
	
	public Config() {
		map = new Map();
	}
	
	protected void save() {
		Jdoer<Map> dbm = JdoerFactory.getMapJdo();
		dbm.save(map);
	}
	
	private Config(int i){}

	public static List<Config> listAll() {
		List<Config> list = new ArrayList<Config>();
		Jdoer<Map> dbm = JdoerFactory.getMapJdo();
		Query query = dbm.prepareQuery();
		query.setOrdering("type ascending");
		Collection<Map> res = dbm.more(query);
		for(Map map : res ) {
			Config conf = new Config(0);
			conf.map = map;
			list.add(conf);
		}
		return list;
	}

	public static Config load(Long id) {
		Jdoer<Map> dbm = JdoerFactory.getMapJdo();
		Config conf = new Config(0);
		conf.map = dbm.load(id);
		return conf;
	}
	
	public String getItem() {
		return map.getItem();
	}
	
	protected void setItem(String item) {
		map.setItem(item);
	}
	
	public Long getId() {
		return map.getKey().getId();
	}
	
	public String getValue() {
		return map.getValue();
	}
	
	public void setValue(String value) {
		map.setValue(value);
	}
	
	public static String getValue(String type, String item) {
		Jdoer<Map> dbm = JdoerFactory.getMapJdo();
		Query query = dbm.prepareQuery();
		query.setFilter("item == itname && type == atype");
		query.declareParameters("String itname, String atype");
		Map map = dbm.unique(query, item, type);
		if ( map != null )
			return map.getValue();
		return "";
	}
	
	public String getType() {
		return map.getType();
	}
	
	protected void setType(String type) {
		map.setType(type);
	}

	public void update() {
		UpdateManager.enableStaticTask();
	}
	

}
